package cn.ltgodm.moj.strategy.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.ltgodm.moj.model.dto.question.JudgeCase;
import cn.ltgodm.moj.model.dto.question.JudgeConfig;
import cn.ltgodm.moj.model.entity.Question;
import cn.ltgodm.moj.model.enums.QuestionJudgeInfomessageEnum;
import cn.ltgodm.moj.model.sandbox.JudgeInfo;
import cn.ltgodm.moj.strategy.JudgeContext;
import cn.ltgodm.moj.strategy.JudgeStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class CPPJudgeStrategy implements JudgeStrategy {
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        log.info("进入java 判题策略");
        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        List<String> resultOuputList = judgeContext.getOutputCaseList();
        Question question = judgeContext.getQuestion();
        if (StringUtils.isBlank(judgeInfo.getMessage())) {
            judgeInfo.setMessage(QuestionJudgeInfomessageEnum.ACCEPTED.getValue());

            //获取题目信息中的输出信息
            List<String> outputList = JSONUtil.toList(question.getJudgeCase(), JudgeCase.class).stream().map(JudgeCase::getOutput).collect(Collectors.toList());
            //对比输出信息
            if (outputList.size() != resultOuputList.size()) {
                judgeInfo.setMessage(QuestionJudgeInfomessageEnum.WRONG_ANSWER.getValue());
                return judgeInfo;
            }
            for (int i = 0; i < outputList.size(); i++) {
                String outputCase = outputList.get(i);
                String resultCase = resultOuputList.get(i);
                if (!outputCase.equals(resultCase)) {
                    judgeInfo.setMessage(QuestionJudgeInfomessageEnum.WRONG_ANSWER.getValue());
                    return judgeInfo;
                }
            }
        }
        //校验判题配置
        JudgeConfig judgeConfig = JSONUtil.toBean(question.getJudgeConfig(), JudgeConfig.class);
        Long memoryLimit = judgeConfig.getMemoryLimit();
        Long timeLimit = judgeConfig.getTimeLimit();
        Long memory = 0L;
        Long time = 0L;
        if (ObjectUtil.isNotNull(judgeInfo.getMemory())) {
            memory = judgeInfo.getMemory() / 1024;
        }
        if (ObjectUtil.isNotNull(judgeInfo.getTime())) {
            time = judgeInfo.getTime();
        }


        if (memory.compareTo(memoryLimit) > 0) {
            judgeInfo.setMessage(QuestionJudgeInfomessageEnum.MEMORY_LIMIT_EXCEEDED.getValue());
            return judgeInfo;
        }

        if (time.compareTo(timeLimit) > 0) {
            judgeInfo.setMessage(QuestionJudgeInfomessageEnum.TIME_LIMIT_EXCEEDED.getValue());
            return judgeInfo;
        }
        //返回正确结果
        return judgeInfo;
    }
}
